<?php
namespace app\shop\library;


use cubox\Cubox;
use app\shop\library\ApiController;

class Member{


    public static $mobileReg = '/^1[3456789]\d{9}$/';
    
    public static $id = '';
    public static string $mobile = '';
    public static bool $login = false;
    public static string $errorMsg = '';
    public static function defineStatus(){
        return [
            'normal' => '正常',
            'lock' => '锁定',
        ];
    }

    public static function getStatusTitle($status){
        return self::defineStatus()[$status]??'';
    }

    public static function formatFront($data){
        $app =  Cubox::app('shop');

        unset($data['password']);

        if ($data['mobile']!=''){
            $data['mobile'] =  substr_replace($data['mobile'],'****',3,4);
        }

        //获取等级名称
        $memberLevel = $app->model('MemberLevel');
        $data['level_title'] = $memberLevel->getId($data['level_id'])['title']??'';
        $data['last_login_time'] = date('Y-m-d H:i:s',$data['last_login_time']); 

        return $data;
    }

    public static function encodeToken($data){
        $app =  Cubox::app('shop');

        $jwt =  new Jwt($app->config('jwt')->toArray());

        $tokenData['member_id'] = $data['member_id'];
        $tokenData['mobile'] = $data['mobile'];

        return $jwt->encode($tokenData);
    }


    public static function headerToken(){
        $app =  Cubox::app('shop');
        
        if (!isset($_SERVER['HTTP_AUTHORIZATION']) || $_SERVER['HTTP_AUTHORIZATION'] ==''){
            self::$errorMsg = '未登陆';
        }else{
            $token = $_SERVER['HTTP_AUTHORIZATION'];
            $jwt = new Jwt($app->config('jwt')->toArray());

            $tokenData = $jwt->decode($token);

            
            if ($tokenData === false){
                self::$errorMsg =  $jwt->errorMsg;
            }else{
                self::$login = true;
                self::$id = $tokenData['member_id'];
                self::$mobile = $tokenData['mobile']??'';
            }
        }
        return self::$login;
    }

    public static function id(){

        if (self::$id==''){
            self::headerToken();
        }

        if (!self::$login){
            throw new \Exception('未登陆');
        }

        return self::$id;
    }

    public static function makePassword($password){
        return md5($password.'bi-shop');
    }

    public static function getLevelTitle($level_id){
        $app =  Cubox::app('shop');

        $level = $app->model('NumberLevel')->getId($level_id);
        
        return $level['title']??'';
    }

    public static function log(string  $type,array $content = []){
        $app =  Cubox::app('shop');
        $log['member_id'] = self::$id;
        $log['type'] = $type;
        $log['content'] = json_encode($content);
        $log['time'] = time();
        $log['ip'] = $_SERVER['REMOTE_ADDR'];
         
        $app->model('MemberLog')->insert($log);
    }

    public static function updateTag($member_id = ''){
        $app =  Cubox::app('shop');
        if ($member_id == '') $member_id = self::id();

        $updateKey = self::cacheName('browsing');

        $cache = $app->cache();

        if (!$cache->exists($updateKey)){

            $tagSeachDeep = $app->config('member')->tagSeachDeep??100;
            $tagSearchType = $app->config('member')->tagSeachType??'time,num';
            $MemberBrowsingHistory = $app->model('MemberBrowsingHistory');
            
            $list  = [];

            if (strpos($tagSearchType,'time')!==false){
                $list = array_merge($list,$MemberBrowsingHistory->field('goods_id')->where('member_id',$member_id)->order('update_time','desc')->limit(0,$tagSeachDeep)->getData());
            }

            if (strpos($tagSearchType,'num')!==false){
                $list = array_merge($list,$MemberBrowsingHistory->field('goods_id')->where('member_id',$member_id)->order('num','desc')->limit(0,$tagSeachDeep)->getData());
            }

            $list =  array_unique(array_column($list,'goods_id'));

            if ($list){
                
                $goods = $app->model('Goods');
                $goodsTagList = $goods->field('tag')->where('goods_id','in',$list)->getData();
                
                $tagList = [];

                foreach($goodsTagList as $v){
                    if ($v['tag'] =='') continue;
                    $tagArr = explode(',',$v['tag']);
                    foreach($tagArr as $tag){
                        if (!isset($tagList[$tag])) $tagList[$tag] = 0;
                        $tagList[$tag]++;
                    }
                }

                if ($tagList){
                    arsort($tagList);

                    $tagLength = $app->config('member')->tagLength??10;

                    $UserTag = '';

                    while(strlen($UserTag)<200 && strlen($UserTag)>0){
                        $UserTag = implode(',',array_keys(array_slice($tagList,0,$tagLength)));
                        $tagLength --;
                    }
                    
                    $UserTagKey =  'shop_user_tag_'.$member_id;
                    $cache->set($UserTagKey,$UserTag);

                    $member = $app->model('Member');
                    $member->updateId($member_id,['tag'=>$UserTag]);
                }                
            }
            
            $tagUpdateTime = $app->config('member')->tagUpdateTime??3600;
            
            $cache->set($updateKey,1,$tagUpdateTime);
        }
    }


    public static function address(){
        $app =  Cubox::app('shop');
        $cacheName = self::cacheName('address');
        $cache = $app->cache();
        if ($cache->exists($cacheName)){
            return json_decode($cache->get($cacheName)??'[]',true);
        }else{
            $MemberAddress = $app->model('MemberAddress');
            $list = $MemberAddress->where('member_id',self::$id)->getData();
            
            foreach ($list as $key => $val){
                $list[$key]['phone'] = substr($val['phone'],0,3).'****'.substr($val['phone'],7); 
            }

            $cache->set($cacheName,json_encode($list));

            return $list;
        }
    }

    public static function clearCache($type=''){
        $app =  Cubox::app('shop');
        $cache = $app->cache();
        $key = self::cacheName($type);
        $cache->delete($key);
    }


    public static function cacheName($type='',$member_id=''){
        if ($member_id=='') $member_id = self::id();
        return  'shopapi_number:'.$member_id.($type!=''?(':'.$type):'');
    }
}